﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcWebRoleUpload.Models;

namespace WebRoleUpload.Controllers
{
    public class FilesController : Controller
    {
        //
        // GET: /Files/

        public ActionResult Index()
        {
            var viewModel = ConstructViewModel();

            return View(viewModel);
        }

        private IStorageHelper ConstructStorageHelper()
        {
            return new BlobStorageHelper();
        }

        private  ViewModelFileUpload ConstructViewModel()
        {
            var repository = ConstructStorageHelper();
            var oldFiles = repository.GetAllPreviouslyUploadedFiles();

            var viewModel = new ViewModelFileUpload();
            viewModel.ExistingFiles = oldFiles;
            return viewModel;
        }

      
        //
        // GET: /Files/Create

        public ActionResult Upload()
        {
            return View();
        } 

        //
        // POST: /Files/Create

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            try
            {
                var repository = ConstructStorageHelper();

                if (file.ContentLength > 0)
                {
                    repository.Save(file.InputStream, file.FileName);
                }


                var viewModel = ConstructViewModel();


                return RedirectToAction("Index", viewModel);

               
            }
            catch
            {
                return View();
            }
        }


        public FileResult Download(string name)
        {

            var repository = ConstructStorageHelper();
            var file = repository.GetFileByName(name);
            if (file != null)
            {


                return File(file.Path, file.ContentType, file.Name);
            }
            else
            {
                return null;
            }

        }

        
    
    }
}
